<!-- 合同管理 -->
<template>
  <el-form inline :model="searchForm" class="search-form">
    <el-form-item label="企业名称">
      <el-autocomplete style="width: 250px" v-model="searchForm.enterpriseName" placeholder="请输入企业名称"
        :fetch-suggestions="queryEnterprise" :trigger-on-focus="false" clearable @select="handleSelectEnterprise" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="resetSearch">重置</el-button>
      <el-button type="primary" @click="handleAddEnterprise">
        新增合同
      </el-button>
    </el-form-item>
  </el-form>
  <el-table :data="contractData" :border="true" style="width: 100%" highlight-current-row>
    <el-table-column prop="enterprisePojo.enterpriseName" label="企业名称" :align="center" width="220"></el-table-column>
    <el-table-column prop="contractNumber" label="合同编号" :align="center" width="180"></el-table-column>
    <el-table-column prop="contractFileName" label="合同文件" :align="center" width="180">
      <template #default="scope">
        <span v-if="scope.row.contractFileName">
          {{ scope.row.contractFileName }}
        </span>
        <span v-if="!scope.row.contractFileName">
          暂未上传合同
        </span>
      </template>
    </el-table-column>
    <el-table-column prop="contractSignDate" label="合同签订日期" :align="center" width="120"></el-table-column>
    <el-table-column prop="contractStartDate" label="合同生效日期" :align="center" width="120"></el-table-column>
    <el-table-column prop="contractEndDate" label="合同到期日期" :align="center" width="120"></el-table-column>
    <el-table-column prop="contractRent" label="租金" :align="center" width="120"></el-table-column>
    <el-table-column prop="contractDeposit" label="押金" :align="center" width="120"></el-table-column>
    <!-- 付款周期: monthly, quarterly, yearly，每月，每季度，每年 -->
    <el-table-column prop="contractPaymentCycle" label="付款周期" :align="center" width="120">
      <template #default="scope">
        <el-tag>
          {{
            scope.row.contractPaymentCycle === 'monthly' ? '每月' :
              scope.row.contractPaymentCycle === 'quarterly' ? '每季度' :
                scope.row.contractPaymentCycle === 'yearly' ? '每年' : '无数据'
          }}
        </el-tag>
      </template>
    </el-table-column>
    <!-- draft:草稿, signed:已签订, expired:已过期, terminated:已终止 -->
    <el-table-column prop="contractStatus" label="合同状态" :align="center" width="120">
      <template #default="scope">
        <el-tag>
          {{
            scope.row.contractStatus === 'draft' ? '草稿' :
              scope.row.contractStatus === 'signed' ? '已签订' :
                scope.row.contractStatus === 'expired' ? '已过期' :
                  scope.row.contractStatus === 'terminated' ? '已终止' : '无数据'
          }}
        </el-tag>
      </template>
    </el-table-column>
    <el-table-column label="操作" width="240" :align="center" fixed="right">
      <template #default="scope">
        <el-button size="small" @click="handleDownFlie(scope.row)">下载合同</el-button>
        <!-- <el-button size="small" @click="handleView(scope.row)">预览</el-button> -->
        <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
        <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page.currentPage"
    :page-sizes="[10, 20, 50]" :page-size="page.size" layout="total, sizes, prev, pager, next, jumper"
    :total="page.total" />


  <!-- 新增/编辑弹窗 -->
  <el-dialog :title="dialogTitle" v-model="addEditDialog" width="800px" :draggable="true" :close-on-click-modal="false">
    <el-form :model="form" ref="formRef" :rules="rules" label-width="100px">

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="企业名称" prop="enterprisePojo.enterpriseId">
            <el-select v-model="form.enterprisePojo.enterpriseId" filterable placeholder="请选择企业名称" clearable
              :disabled="isEdit">
              <el-option v-for="item in enterpriseData" :key="item.enterpriseId" :label="item.enterpriseName"
                :value="item.enterpriseId" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同编号" prop="contractNumber">
            <el-input v-model="form.contractNumber"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="签订日期" prop="contractSignDate">
            <el-date-picker v-model="form.contractSignDate" type="date" value-format="YYYY-MM-DD"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="生效日期" prop="contractStartDate">
            <el-date-picker v-model="form.contractStartDate" type="date" value-format="YYYY-MM-DD"></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="到期日期" prop="contractEndDate">
            <el-date-picker v-model="form.contractEndDate" type="date" value-format="YYYY-MM-DD"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同状态" prop="contractStatus">
            <el-select v-model="form.contractStatus">
              <el-option label="已签订" value="signed"></el-option>
              <el-option label="已过期" value="expired"></el-option>
              <el-option label="已终止" value="terminated"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="租金" prop="contractRent">
            <el-input v-model.number="form.contractRent" type="number"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="押金" prop="contractDeposit">
            <el-input v-model.number="form.contractDeposit" type="number"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="付款周期" prop="contractPaymentCycle">
            <el-select v-model="form.contractPaymentCycle">
              <el-option label="每月" value="monthly"></el-option>
              <el-option label="每季度" value="quarterly"></el-option>
              <el-option label="每年" value="yearly"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="合同内容" prop="contractNotes">
        <el-input v-model="form.contractNotes" type="textarea" :rows="6"></el-input>
      </el-form-item>
      <!-- 保存合同信息按钮 -->
      <el-form-item class="form-actions">
        <el-button type="primary" @click="saveContractInfo">保存合同信息</el-button>
        <el-button @click="closeSave">关闭弹框</el-button>
      </el-form-item>
      <el-form-item label="合同文件" prop="fileList" v-if="contractId">
        <el-upload v-model:file-list="form.fileList" :http-request="customUpload" :limit="1" multiple
          :file-size="20 * 1024 * 1024" :before-upload="handleBeforeUpload" :on-exceed="handleExceed" drag
          :on-remove="handleRemove">
          <!-- 上传按钮图标 -->
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <template #tip>
            <div class="el-upload__tip">
              支持上传 jpg、jpeg、png、pdf 等格式文件，大小不超过 50MB，最多上传 1 个文件
            </div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
  </el-dialog>

</template>

<script setup>
import request from '@/api/request';
import { downloadContract } from '@/api/contract'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus';
import { onMounted, ref, reactive, nextTick, getCurrentInstance } from 'vue';
defineEmits(['callUpdateLoadAnalysisMethod']);
// 获取组件实例（用于 emit 事件）
const { emit } = getCurrentInstance();

// 搜索表单
const searchForm = ref({
  enterpriseName: null,
  parkId: null,
  selectedValue: null,
  isFollowed: null,
  buildingId: null,
  floor: null
})
const contractData = ref([])
const center = 'center'
// 分页参数
const page = ref({
  current: 1,
  size: 10,
  total: 1
})
//新增编辑弹框
const dialogTitle = ref('新增合同信息');
const isEdit = ref(false)
const addEditDialog = ref(false)
// 合同ID（保存成功后由后端返回）
const contractId = ref('')
const formRef = ref(null);
const form = reactive({
  contractId: null,
  contractNumber: null,
  contractSignDate: null,
  contractStartDate: null,
  contractEndDate: null,
  contractRent: null,
  contractDeposit: null,
  contractPaymentCycle: 'yearly',
  contractStatus: null,
  contractNotes: null,
  enterprisePojo: {},
  parkInfo: {},
  fileList: []
});
//表单规则
const rules = {

  'enterprisePojo.enterpriseId': [
    { required: true, message: '请输入企业全称', trigger: 'blur' }
  ],
  contractNumber: [
    { required: true, message: '请输入合同编号', trigger: 'blur' }
  ],
  contractSignDate: [
    { required: true, message: '请选择签订日期', trigger: 'blur' }
  ],
  contractStartDate: [
    { required: true, message: '请选择生效日期', trigger: 'blur' }
  ],
  contractEndDate: [
    { required: true, message: '请选择到期日期', trigger: 'blur' }
  ],
  contractRent: [
    { required: true, message: '请输入租金', trigger: 'blur' }
  ],
  contractDeposit: [
    { required: true, message: '请输入押金', trigger: 'blur' }
  ],
  contractPaymentCycle: [
    { required: true, message: '请选择付款周期', trigger: 'blur' }
  ],
  contractStatus: [
    { required: true, message: '请输入合同状态', trigger: 'blur' }
  ],
  fileList: [
    { required: true, message: '请上传文件', trigger: 'change' }
  ]
};
//企业下拉数据列表
const enterpriseData = ref([]);
const props = defineProps({
  parkData: {
    type: Object,
    default: () => ([])
  }
});
// 初始化数据
onMounted(() => {
  //加载数据表格
  loadContractData()
  //查询新增编辑企业下拉
  loadEnterpriseData()
});
//点击查询
const handleSearch = () => {
  loadContractData()
}
/**
 * 选中下拉项时触发
 * @param {Object} item - 选中的企业对象（包含 value、id 等字段）
 */
const handleSelectEnterprise = (item) => {
  searchForm.enterpriseName = item.value
  loadContractData()
}
//点击重置
const resetSearch = () => {
  searchForm.value = {}
  loadContractData()
}
//点击新增合同
const handleAddEnterprise = async () => {
  resetForm()
  addEditDialog.value = true
  // 等待弹窗和表单渲染完成后，再重置验证状态
  await nextTick();
  isEdit.value = false
  formRef.value.resetFields();
}

//文件下载
const handleDownFlie = async (row) => {
  downloadContract(
    {
      contractId: row.contractId
    },
    'enterpriseContract/download-file'
  )
}

//点击编辑
const handleEdit = async (row) => {
  resetForm()
  addEditDialog.value = true
  // 等待弹窗和表单渲染完成后，再重置验证状态
  await nextTick();
  isEdit.value = true
  formRef.value.clearValidate();
  contractId.value = row.contractId
  Object.keys(form).forEach(key => {
    if (row[key] !== undefined) {
      form[key] = row[key];
    }
  });
  // 编辑时，回显合同文件到 form.fileList
  if (row.contractFileName) {
    // 构造符合 UploadFile 格式的对象
    form.fileList = [
      {
        name: row.contractFileName, // 后端返回的文件名
        url: row.contractFilePath,  // 后端返回的文件访问路径（若需预览）
        uid: row.contractFileHash || new Date().getTime(), // 唯一标识（用合同ID或时间戳保证唯一）
        status: 'success' // 标记为“已上传成功”状态
      }
    ];
  } else {
    // 无文件时，置空数组
    form.fileList = [];
  }
  enterpriseData.value.push(row.enterprisePojo)
}
const resetForm = () => {
  form.contractId = null;
  form.contractNumber = null;
  form.contractSignDate = null;
  form.contractStartDate = null;
  form.contractEndDate = null;
  form.contractRent = null;
  form.contractDeposit = null;
  form.contractPaymentCycle = 'yearly';
  form.contractStatus = null;
  form.contractNotes = null;
  form.enterprisePojo = {}; // 重置为空对象（清除之前的企业信息）
  form.parkInfo = {}; // 重置为空对象（清除之前的园区信息）
  form.fileList = []; // 重置为空数组（清除之前的文件列表）
};

//点击删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除当前合同信息吗?')
    .then(() => {
      const loading = ElLoading.service({
        lock: true,
        text: '正在删除...',
        background: 'rgba(0, 0, 0, 0.7)',
      })

      request.get('/enterpriseContract/removeContract', {
        params: {
          contractId: row.contractId
        }
      }).then(data => {
        if (data.success) {
          ElMessage.success('删除成功');
          loadContractData()
          loadEnterpriseData()//删除后重新查询新增下拉
          emit('callUpdateLoadAnalysisMethod');
        } else {
          ElMessage.error(data.message);
        }
        loading.close()
      }).catch(err => {
        ElMessage.error('删除异常' + err);
        loading.close()
      })
    })
    .catch(() => {
      // catch error
    }).finally(() => {
    })
}


const loadContractData = async () => {

  // const loading = ElLoading.service({
  //   lock: true,
  //   text: '正在初始化页面数据...',
  //   background: 'rgba(0, 0, 0, 0.7)',
  // })
  try {
    const resData = await request.get('/enterpriseContract/getEnterpriseContractPage', {
      params: {
        pageNum: page.value.current,
        pageSize: page.value.size,
        enterpriseName: searchForm.value.enterpriseName,
      }
    })
    if (resData.success) {
      contractData.value = resData.data.list
      page.value.total = data.data.total
    }
  } catch (err) {

  } finally {
    // loading.close()
  }
}
//查询新增编辑企业下拉
const loadEnterpriseData = async (name) => {
  const res = await request.get("enterpriseContract/getEnterpriseNameData", {
    params: { enterpriseName: name }  // 传递搜索关键词
  })
  if (res.success) {
    enterpriseData.value = res.data
  } else {
    enterpriseData.value = []
  }
}

//保存合同信息
const saveContractInfo = async () => {
  try {
    await formRef.value.validate()
    const formData = JSON.parse(JSON.stringify(form));
    const res = await request.post('/enterpriseContract/addContract', formData)
    if (res.success) {
      ElMessage.success('数据保存成功')
      contractId.value = res.data
      form.contractId = res.data
      emit('callUpdateLoadAnalysisMethod');
    } else {
      ElMessage.error('表单提交失败：' + res.message)
    }
  } catch (err) {
    console.log('表单验证失败：', err)
    ElMessage.error('表单验证失败')
  }
}
const closeSave = () => {
  addEditDialog.value = false
  contractId.value = null
  form.contractId = null
  loadContractData()
}

// 自定义上传函数（核心：携带contractId）
const customUpload = async (options) => {
  const { file, onSuccess, onError } = options

  // 确保合同ID已存在（理论上不会触发，因为上传区域在contractId存在时才显示）
  if (!contractId.value) {
    ElMessage.error('请先保存合同信息')
    onError('未获取到合同ID')
    return
  }

  try {
    // 创建FormData，包含文件和合同ID
    const formData = new FormData()
    formData.append('file', file)  // 文件字段（与后端一致）
    formData.append('contractId', contractId.value)  // 携带合同ID（关键！）

    // 发送上传请求
    const response = await request.post(
      '/enterpriseContract/upload-file',  // 合同文件上传接口
      formData, {
      headers: {
        'Authorization': 'Bearer ' + localStorage.getItem('park-token'),
        'Content-Type': 'multipart/form-data'
      },
      // 可选：显示上传进度
      onUploadProgress: (e) => {
        const percent = Math.round((e.loaded / e.total) * 100)
        options.onProgress({ percent })  // 传递进度给组件
      }
    }
    )

    if (response.success) {
      ElMessage.success('文件上传成功，已绑定到合同')
      onSuccess(response.data)  // 通知组件上传成功
    } else {
      ElMessage.error('文件上传失败：' + response.message)
      onError(response.data)
    }
  } catch (err) {
    ElMessage.error('上传请求失败：' + (err.message || '网络错误'))
    onError(err)
  }
}
// 上传前校验（补充验证文件类型和大小）
const handleBeforeUpload = (file) => {
  // 验证文件类型（el-upload 的 accept 只是前端过滤，这里做二次校验）
  // const acceptTypes = ['.jpg', '.jpeg', '.png', '.pdf', '.doc', '.docx', ".xls", ".xlsx"]
  // const fileExt = '.' + file.name.split('.').pop().toLowerCase()
  // if (!acceptTypes.includes(fileExt)) {
  //   ElMessage.error('仅支持上传 jpg、jpeg、png、pdf、doc、docx、xls、xlsx 格式文件')
  //   return false  // 阻止上传
  // }

  // 验证文件大小（el-upload 的 file-size 只是前端限制，这里做二次校验）
  if (file.size > 50 * 1024 * 1024) {
    ElMessage.error('文件大小不能超过 50MB')
    return false  // 阻止上传
  }

  return true  // 允许上传
}

// 超过文件数量限制时触发
const handleExceed = () => {
  ElMessage.warning('最多只能上传 1 个文件')
}

// 移除文件时触发
const handleRemove = () => {
  // 移除后触发表单验证（确保必填项校验生效）
  formRef.value.validateField('fileList')
}

// 分页-当前页改变
const handleCurrentChange = (val) => {
  page.value.current = val
  loadContractData()
}

// 分页-每页条数改变
const handleSizeChange = (val) => {
  page.value.size = val
  loadContractData()
}

const searchTimer = ref(null)  // 防抖计时器（ref 用于响应式存储）
const queryEnterprise = (queryString, callback) => {
  // 清除上一次的定时器（防抖）
  clearTimeout(searchTimer.value)

  // 300ms 防抖：输入停止后再请求
  searchTimer.value = setTimeout(async () => {
    // 输入为空时不请求
    if (!queryString.trim()) {
      callback([])
      return
    }
    try {
      const res = await request.get("enterpriseContract/getEnterpriseNameData", {
        params: { enterpriseName: queryString }  // 传递搜索关键词
      })
      if (res.success) {
        if (res.data.length == 0) {
          callback([])
          return
        }
        // 格式化数据：下拉框需要 { value: '显示文本', ...其他字段 } 结构
        const suggestions = res.data.map(enterprise => ({
          value: enterprise.enterpriseName,  // 下拉框中显示的企业名称
          id: enterprise.enterpriseId,       // 企业ID（可选，用于后续业务）
          // 可添加其他需要的字段（如地址、代码等）
        }));
        // 将数据回传给下拉框
        callback(suggestions)
      } else {
        callback([])  // 出错时返回空数组
      }

    } catch (error) {
      console.error('获取企业列表失败：', error)
      callback([])  // 出错时返回空数组
    }
  }, 300)
}

</script>
<style scoped>
.search-form {
  margin-bottom: 16px;
  text-align: left;
}

/* 按钮区域靠右对齐 */
.form-actions {
  display: flex;
  justify-content: flex-end;
  /* 靠右对齐 */
  margin-top: 10px;
  /* 与上方内容拉开距离 */
  margin-left: 55%;
}

:deep(.el-upload-dragger) {
  padding: 10px;
  /* 缩小内边距，默认 padding 较大 */
}
</style>